package com.yydlz.users.service.impl;


import com.yydlz.users.service.UsersService;
import com.yydlz.users.utils.HttpClientUtil;
import com.yydlz.users.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Map;

@Service("LoginService")
public class UsersServiceImpl implements UsersService {

    @Autowired
    private RedisUtil redisUtil;

    private static String corpid = "wx1d3765eb45497a18";
    private static String corpsecret = "AmKs5ayubNZPe3STFJVnn1wLbirDDc054iG7JMuwpRo";


    /**
     * 获取access_token
     * @return
     */
    @Override
    public String getAccessToken(){
        String accessToken;

        //优先从缓存里面取accessToken
        if(redisUtil.hasKey("accessToken")){
            accessToken = (String) redisUtil.get("accessToken");
        }
        //如果缓存没有accessToken，则调接口获取，并存储在缓存中
        else{
            //获取access_token
            String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret;
            accessToken = (String) HttpClientUtil.getHttpClient(url).get("access_token");

            //将access_token存到redis中，并设置失效时间为2小时
            redisUtil.set("accessToken",accessToken);
            redisUtil.expire("accessToken",7200);
        }

        return accessToken;
    }


    /**
     * 获取用户id
     * @param code
     * @return
     */
    @Override
    public String getUserId(String code){
        String accessToken = getAccessToken();

        String url ="https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token="+accessToken+"&code="+code;

        String userId = (String) HttpClientUtil.getHttpClient(url).get("UserId");
        return userId;
    }


    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    @Override
    public Map<String,Object> getUserInfo(String userId){
        //获取accessToken
        String accessToken = getAccessToken();

        //获取用户详细信息
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken+"&userid="+userId;
        Map<String,Object> map = HttpClientUtil.getHttpClient(url);

        return map;
    }


    /**
     * 构造网页授权链接
     * @return
     */
    @Override
    public String Oauth2API(String redirectUri){
        //使用urlencode对链接进行处理
        try {
            redirectUri = java.net.URLEncoder.encode(redirectUri, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+corpid+"&redirect_uri="+redirectUri+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
        return url;
    }
}
